/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
//根据二叉树创建字符串 力扣606 （难点在于添加括号和前序遍历的条件要明白清楚）
class Solution10 {
    StringBuilder s = new StringBuilder();

    public String tree2str(TreeNode root) {
        if (root == null) {
            return "";
        }
        preorder(root); // 调用前序遍历
        return s.toString();
    }

    void preorder(TreeNode root) {
        if (root == null) {
            return;
        }

        s.append(root.val); // 添加当前节点值

        if (root.left != null) {
            s.append("(");
            preorder(root.left); // 遍历左子树
            s.append(")");
        } else if (root.right != null) {
            s.append("()"); // 左子树为空，但右子树不为空时，添加空括号
        }

        if (root.right != null) {
            s.append("(");
            preorder(root.right); // 遍历右子树
            s.append(")");
        }
    }
}